<!-- phoneManage -->
<template>
  <div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="手机" prop="phone">
        <el-input
          type="phone"
          v-model="ruleForm.phone"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="send_captcha"
          :disabled="isDisabled"
          >{{ buttonName }}</el-button
        >
      </el-form-item>
      <el-form-item label="验证码" prop="captcha">
        <el-input v-model.number="ruleForm.captcha"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "phoneManage",
  data() {
    var checkCaptcha = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("验证码不能为空"));
      }
      callback();
    };
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机"));
      } else if (!(/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/).test(value)) {
        callback(new Error("手机格式不对"));
      } else {
        this.canPhone = true
        callback();
      }
    };
    return {
      CountDown: 60,
      buttonName: "发送验证码",
      isDisabled: true,
      canPhone:false,
      captcha_id: "",
      captcha_dest_addr:"",
      ruleForm: {
        phone: "",
        captcha: "",
      },
      rules: {
        phone: [{ validator: validatePhone, trigger: "blur" }],
        captcha: [{ validator: checkCaptcha, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("submit!");
          this.$store
            .dispatch("user/editSelfSafe", {
              captchaId: this.captcha_id,                                                     
              captcha: this.ruleForm.captcha,
              captcha_dest_addr: this.captcha_dest_addr,
              password: null,
              phoneNumber: this.ruleForm.phone,
              email: null,
            })
            .then((data) => {
              this.$store.commit("user/SET_USERINFO", data.data);
              this.$message.success("手机更绑成功");
              location.reload()
            })
            .catch((error) => {
              console.log(error);
              this.$message.error("手机更绑失败，请稍后重试");
            });
        } else {
          this.$message.error("错误的提交，请稍后重试");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    send_captcha() {
      if (!this.canPhone) {
          this.$message.warning("请先输入正确的手机号")
          return 
      }
      this.isDisabled = true;
      let timerId = setInterval(() => {
        this.CountDown--;
        this.buttonName = this.CountDown + "秒后重试";
        if (this.CountDown <= 0) {
          clearInterval(timerId);
          this.buttonName = "重新发送";
          this.CountDown = 60;
          this.isDisabled = false;
        }
      }, 1000);

      this.$store
        .dispatch("login/sms", this.ruleForm.phone)
        .then((data) => {
          this.$message.success(data);
          this.captcha_id = this.$store.state.login.captcha_id;
          this.captcha_dest_addr = this.ruleForm.phone;
        })
        .catch((error) => {
          this.$message.error("验证码发送失败，请重试");
          clearInterval(timerId);
          this.buttonName = "重新发送";
          this.CountDown = 60;
          this.isDisabled = false;
        });
    },
  },
  created() {
    if (sessionStorage.getItem("CountDownInfo")) {
      this.CountDown = JSON.parse(
        sessionStorage.getItem("CountDownInfo")
      ).CountDown;
      this.isDisabled = JSON.parse(
        sessionStorage.getItem("CountDownInfo")
      ).isDisabled;
      this.captcha_id = JSON.parse(
        sessionStorage.getItem("CountDownInfo")
      ).captcha_id;
    }
    if (this.isDisabled) {
      let timerId = setInterval(() => {
        this.CountDown--;
        this.buttonName = this.CountDown + "秒后重试";
        if (this.CountDown <= 0) {
          clearInterval(timerId);
          this.buttonName = "重新发送";
          this.CountDown = 60;
          this.isDisabled = false;
        }
      }, 1000);
    }
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem(
        "CountDownInfo",
        JSON.stringify({
          CountDown: this.CountDown,
          isDisabled: this.isDisabled,
          captcha_id: this.captcha_id,
        })
      );
    });
  },
};
</script>

<style lang='scss' scoped>
</style>